<template>
  <div class="battle-room">
    <div class="battle-detail" v-if="detail">
      <div class="header">
        <div class="header-left">活动编号：{{ detail.room.id }} （{{detail.room.is_reverse?'逆运':'天命'}}）</div>

        <div class="header-right">
          <!-- <img src="@/static/img/battle/rule.png" /> -->
          <!-- <img src="@/static/img/battle/history.png" /> -->
          <!-- <img src="@/static/img/battle/back.png" /> -->
          <div @click="isOpenSound = !isOpenSound">
            <el-tooltip
              :content="isOpenSound ? '关闭音效' : '打开音效'"
              v-if="!isMobile"
            >
              <img
                v-if="!isOpenSound"
                src="@/static/img/battle/audio-close.png"
              />
              <img v-else src="@/static/img/battle/audio-open.png" />
            </el-tooltip>
            <template v-else>
              <img
                v-if="!isOpenSound"
                src="@/static/img/battle/audio-close.png"
              />
              <img v-else src="@/static/img/battle/audio-open.png" />
            </template>
          </div>
          <div @click="openRuleDialog">规则</div>
          <div @click="handleToBattleHistory">记录</div>
          <div @click="handleBack">返回</div>
        </div>
      </div>

      <div class="main">
        <!-- 对战信息 -->
        <div class="battle-info">
          <!-- 回合数 -->
          <div class="round">
            <div class="round-progress">
              <span>{{ round }}/{{ detail.room.rounds }}</span>
              <span>回合</span>
            </div>
            <div class="round-status">{{ battleStatus }}</div>
          </div>
          <!-- 箱子列表 -->
          <div class="box-list battle-scrollbar" ref="boxListRef">
            <div
              class="box-item"
              v-for="(box, i) in detail.boxs"
              :class="{ active: i === round - 1 }"
            >
              <img :src="box.box_img" @click="handleClickBox(box.box_id)" />
            </div>
          </div>
          <!-- 分享房间 -->
          <div class="share-button">
            <v-btn color="#8E7EED" @click="shareBattleRoom">分享房间</v-btn>
          </div>
        </div>

        <!-- 参与人员 -->
        <div
          style="width: 100%; margin-top: 30px"
          class="d-flex battle-users"
          v-if="detail"
          v-loading="loading.join"
        >
          <battle-block
            v-for="(block, i) in blocks"
            :user="block.user"
            :awards="block.awards"
            :room="detail.room"
            :key="block.key"
            :loading="loading.join"
            :skin-list="skinList"
            :ref="(ref) => setBlockRef(i, ref)"
            :user-role="userRole"
            :round="round"
            :comfort-award="comfortAward"
            :has-robot="hasRobot"
            @join-battle="(isRobot,password) => joinBattle(i, isRobot,password)"
            @share="shareBattleRoom"
          ></battle-block>
          <!-- <battle-block></battle-block> -->
        </div>
      </div>
    </div>

    <battle-detail-bottom ref="bottomRef" />
    <battle-rule ref="battleRuleRef"></battle-rule>
  </div>
</template>
<script lang="ts">
import { ElMessage } from "element-plus";
import { defineComponent, nextTick, computed, ref, watchEffect } from "vue";
import BattleBlock from "./components/BattleBlock/BattleBlock.vue";
import BattleSkinItem from "./components/BattleSkinItem.vue";
import { useBattleRoomDetail } from "./services";
import BattleDetailBottom from "./components/BattleDetailBottom.vue";
import BattleRule from "./components/BattleRule.vue";
import { useRouter } from "vue-router";

export default defineComponent({
  setup() {
    const router = useRouter();

    const {
      loading,
      detail,
      joinRoom,
      round,
      blocks,
      skinList,
      userRole,
      comfortAward,
      hasRobot,
      isOpenSound,
    } = useBattleRoomDetail({
      onRound: (data) => {
        nextTick(() => {
          blockRef.forEach((block, i) => {
            block.start(data);
          });
        });
      },
    });

    const blockRef: any[] = [];
    const bottomRef = ref<any>();
    const boxListRef = ref<any>();
    const battleRuleRef = ref<any>();

    watchEffect(() => {
      const index = round.value - 1;

      nextTick(() => {
        if (index < 0) return;

        if (boxListRef.value) {
          const elements = boxListRef.value.querySelectorAll(".box-item");
          const element = elements[index];

          const { offsetLeft, offsetWidth } = element;

          const left = offsetLeft - boxListRef.value.clientWidth + offsetWidth;

          if (left > 0) {
            boxListRef.value.scroll({
              top: 0,
              left,
              behavior: "smooth",
            });
          }
        } else {
          console.log("没找到元素");
        }
      });
    });

    return {
      detail,
      joinBattle: (i: number, isRobot: boolean,password:string) => {
        const index = i + 1;
        return joinRoom(index, isRobot,password).then(() => {
          console.log("加入房间成功");
        });
      },
      shareBattleRoom: () => {
        const input = document.createElement("input");
        input.setAttribute("readonly", "readonly");
        input.value = location.href;
        document.body.appendChild(input);
        input.select();

        const result = document.execCommand("Copy");
        if (result) {
          ElMessage.success("已复制房间链接，分享给好友一起对战吧！");
          document.body.removeChild(input);
        } else {
          ElMessage.error("复制链接失败，请手动复制该页面地址");
        }
      },
      openRuleDialog() {
        battleRuleRef.value.open();
      },
      handleToBattleHistory() {
        router.push("/battle/history");
      },
      handleBack() {
        const { back } = router.options.history.state;
        if (back) {
          router.back();
        } else {
          router.push("/battle");
        }
      },

      loading,
      round,
      blocks,
      skinList,
      userRole,
      comfortAward,
      hasRobot,
      bottomRef,
      boxListRef,
      battleRuleRef,
      isOpenSound,
      setBlockRef(i: number, ref: any) {
        blockRef[i] = ref;
      },

      battleStatus: computed(() => {
        const status = detail.value?.room.status;
        if (status === -1) return "超时";
        if (status === 0) return "等待中";
        if (status === 1) return "进行中";
        if (status === 2) return "已结束";
      }),

      handleClickBox(id: number) {
		let rid = detail.value.room.id;
        bottomRef.value.open(id, rid);
      },
      isMobile: window.screen.width <= 600,
    };
  },

  components: {
    BattleBlock,
    BattleSkinItem,
    BattleDetailBottom,
    BattleRule,
  },
});
</script>

<style scope lang="scss">
.battle-detail {
  width: 100%;
  max-width: 1300px;
  margin: 0 auto;
}

.header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #28253b;
  margin-top: 30px;

  .header-left {
    font-size: 16px;
    font-weight: 500;
    color: rgba(255, 255, 255, 0.56);
  }

  .header-right {
    display: flex;
    font-size: 16px;
    font-weight: 500;
    color: rgba(255, 255, 255, 0.56);

    > * {
      margin-right: 30px;
      cursor: pointer;
      display: flex;
      align-items: center;

      &:last-child {
        margin-right: 0 !important;
      }
    }

    img {
      width: 26px;
      height: 26px;
      margin-right: 8px;
    }
  }
}

.main {
  background: #1c192a;
  padding-bottom: 30px;

  .battle-info {
    display: flex;
    align-items: center;

    .round {
      width: 152px;
      height: 152px;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      flex: none;

      .round-progress {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        background: rgba(40, 37, 59, 0.39);
        border: 4px solid #8e7eed;
        box-shadow: 0px 0px 24px rgba(142, 126, 237, 0.78);
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;

        span:first-child {
          font-size: 22px;
          line-height: 22px;
          font-weight: bold;
          color: #ffffff;
        }

        span:last-child {
          font-size: 14px;
          line-height: 14px;
          color: rgba(255, 255, 255, 0.7);
        }
      }

      .round-status {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        font-size: 18px;
        color: rgba(255, 255, 255, 0.56);
        text-align: center;
      }
    }

    .box-list {
      display: flex;
      flex-wrap: nowrap;
      flex: 1;
      overflow-x: auto;
      overflow-y: hidden;
      position: relative;

      .box-item {
        width: 96px;
        height: 96px;
        flex: none;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        transition: transform 0.3s linear;

        &.active {
          background: url(@/static/img/battle/box-active.png) center no-repeat;
          background-size: 90% 90%;
          transform: scale(1.3);
          transform-origin: center;
          filter: brightness(120%);
        }

        img {
          width: 66px;
        }
      }
    }

    .share-button {
      // width: 207px;
      margin: 0 32px;
      flex: none;

      > * {
        width: 86px;
        font-size: 12px;
        color: #fff;
      }
    }
  }
}

.battle-users {
  > * {
    margin-left: 21px;

    &:first-child {
      margin-right: 0;
    }
  }
}
</style>

<style scoped lang="scss">
@media screen and (max-width: 600px) {
  .battle-detail {
    width: 100%;
  }

  .battle-info {
    padding-left: 16px;

    .round {
      width: 48px;
      height: 100px;

      .round-progress {
        width: 48px;
        height: 48px;

        span:first-child {
          font-size: 13px;
        }
        span:last-child {
          font-size: 12px;
        }
      }

      .round-status {
        font-size: 14px;
      }
    }

    .box-list {
      margin-left: 8px;

      .box-item {
        width: 50px;
        height: 50px;

        img {
          width: 30px;
        }
      }
    }

    .share-button {
      // width: 85px;
      // height: 24px;
      margin-left: 32px;
      margin-right: 15px;
    }
  }

  .battle-users {
    > * {
      margin-left: 1px;
    }
  }

  .header {
    padding: 8px;

    .header-left {
      font-size: 14px;
    }

    .header-right {
      font-size: 14px;
      padding-right: 10px;
      // padding: 0 10px;

      > * {
        margin-right: 16px;
      }

      img {
        width: 17px;
        height: 17px;
        margin-right: 5px;
      }
    }
  }
}
</style>
